﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Models;
using App.Models.Pager;
using App.Views.ViewModels;
using BLL;

namespace App.Controllers
{
    public class CosmeticServiceController : BaseController
    {
        //
        // GET: /FaceLiftingService/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List(int? page, int? rows, string order)
        {
            dbe.ContextOptions.ProxyCreationEnabled = false;
            dbe.ContextOptions.LazyLoadingEnabled = false;

            int offset = (page ?? 1 - 1) * (rows ?? 10);
            PagedList<tb_CosmeticRecords> list = null;
            if ("asc" == order)
            {
                list = dbe.tb_CosmeticRecords.OrderBy(m => m.CosmeticNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            else
            {
                list = dbe.tb_CosmeticRecords.OrderByDescending(m => m.CosmeticNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            PagedList<CosmeticServiceEditViewModel> data = new PagedList<CosmeticServiceEditViewModel>(
                                                list.CurrentPageIndex, list.PageSize, list.total);
            data.rows.AddRange(from f in list.rows select new CosmeticServiceEditViewModel
                               {
                                   CosmeticNO = f.CosmeticNO,
                                   ServiceNo = f.ServiceNo,
                                   DeadNO = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNo == f.ServiceNo).DeadNO,
                                   Beautician = f.Beautician,
                                   StartTime = f.StartTime,
                                   EndTime = f.EndTime==null?DateTime.Now:f.EndTime.Value
                               });

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Create()
        {
            var vmodel = GetServiceItemList("", Utils.COSMETIC_SERVICE_TYPE);
            return PartialView("UCServicesItemList", vmodel);
        }


        [HttpPost]
        public ActionResult Create([Bind(Exclude = "ItemList")]CosmeticServiceEditViewModel vmodel)
        {
            try
            {
                var serviceNo = GenServiceNo();
                //保存服务费用
                AddServiceItems(vmodel.DeadNO, serviceNo, vmodel.SelectedItemList);

                //保存整容服务记录
                var m = new tb_CosmeticRecords
                {
                    CosmeticNO = GenCosmeticNO(),
                    ServiceNo = serviceNo,
                    StartTime = vmodel.StartTime,
                    EndTime = vmodel.EndTime,
                    Beautician = vmodel.Beautician
                };
                dbe.tb_CosmeticRecords.AddObject(m);
                dbe.SaveChanges();
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { success = false, msg = "保存出错！" }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Edit(string id)
        {
            var model = dbe.tb_CosmeticRecords.FirstOrDefault(m => m.CosmeticNO == id);
            var vmodel = GetServiceItemList(model.ServiceNo, Utils.COSMETIC_SERVICE_TYPE);
            return PartialView("UCServicesItemList", vmodel);
        }

        [HttpPost]
        public ActionResult Edit(string id, [Bind(Exclude = "ItemList")]CosmeticServiceEditViewModel vmodel)
        {
            try
            {
                EditServiceItems(vmodel.SelectedItemList, vmodel.DeadNO, vmodel.ServiceNo);

                var model = dbe.tb_CosmeticRecords.FirstOrDefault(m => m.CosmeticNO == vmodel.CosmeticNO);
                model.StartTime = vmodel.StartTime;
                model.EndTime = vmodel.EndTime;
                model.Beautician = vmodel.Beautician;
                
                dbe.SaveChanges();
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { success = false, msg = "保存出错！" }, JsonRequestBehavior.AllowGet);
            }
        }


        [HttpPost]
        public ActionResult Delete(string ids)
        {
            try
            {
                string[] idList = ids.Split('&');
                foreach (var id in idList)
                {
                    var obj = dbe.tb_CosmeticRecords.FirstOrDefault(m => m.CosmeticNO == id);
                    dbe.tb_CosmeticRecords.DeleteObject(obj);
                    //删除服务收费
                    DeleteServiceItems(obj.ServiceNo);
                }

                dbe.SaveChanges();
                var res = new { success = true };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "删除出错！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult SelectBeautician(string st, string et)
        {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));

            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now.AddHours(4);
            try
            {
                stime = DateTime.Parse(st);
                etime = DateTime.Parse(et);
                if (stime.CompareTo(DateTime.MinValue) <= 0) stime = DateTime.Now;
                if (stime.CompareTo(DateTime.MinValue) <= 0) etime = stime;

            }
            catch
            {

            }

            SysPersonBLL bll = new SysPersonBLL();
            var list = bll.GetByDepartment(Utils.COSMETIC_DEPARTMENT);
            //统计在StartTime - EndTime 这个段时间已经预约或在用房间
            // 表示该位置已经预约或在用 
            var useds = dbe.tb_CosmeticRecords.Where(m => m.StartTime <= etime && m.EndTime > stime);
            
            var usedIdList = useds.Select(m => m.Beautician).ToList();
            var usedList = useds.ToList();
            var lv = new List<BeauticainStatusViewModel>();
            foreach (var c in list)
            {
                string status = "空闲";
                string hintMsg = "";
                int pos = usedIdList.IndexOf(c.Name);
                if (pos >= 0)
                {
                    status = "在用";
                    hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", usedList[pos].StartTime, usedList[pos].EndTime);
                }
                var lvi = new BeauticainStatusViewModel
                {
                    BId = c.Name,
                    BName = c.MyName,
                    Status = status,
                    Remark = hintMsg
                };
                lv.Add(lvi);
            }     
            return PartialView(lv);
        }
    }
}
